package com.bsoft.exchange.controller.appointmentandregistration;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.pojo.*;
import com.bsoft.exchange.service.YBService;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bsoft.exchange.response.ResponseEntity;
import com.bsoft.exchange.response.ResponseStatus;
import com.bsoft.exchange.service.AppointmentService;
import com.bsoft.exchange.service.CanceledWorksService;
import com.bsoft.exchange.service.TakenumberService;
import com.bsoft.exchange.util.BaseResponse;
import com.bsoft.exchange.util.Constant;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@Api("swagger测试控制器")
@RestController
@RequestMapping(value = "appointment")
public class AppointmentController {

    private static final Logger logger = LoggerFactory.getLogger(AppointmentController.class);

    @Autowired
    Mapper dozerMapper;

    @Autowired
    AppointmentService appointmentService;

    @Autowired
    CanceledWorksService canceledWorksService;

    @Autowired
    TakenumberService TakenumberService;

    @Autowired
    YBService ybService;

    @ApiOperation(value = "预约支付", notes = "入参：hospitalCode：机构id ； hisOrderNumber ：医院挂号流水号 ；outOrderNumber：商户订单号；"
            + "payMode：支付方式；agtOrderNumber：对应收单机构；payAmount ：付款金额； payTime：实际支付时间；notify：支付成功通知信息；channelOrderNumber：渠道商订单号；outpatientType：门诊类型;" +
            "cardNum:医保卡号;yblsh:医保流水号")
    @ResponseBody
    @RequestMapping(value = "/appointmentPay", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity appointmentPay(@RequestBody AppointmentPayPojo appointmentPayPojo) {
        logger.info("===== appointmentPayPojo : {} ========",appointmentPayPojo);

        ResponseEntity entity = new ResponseEntity();

        BaseResponse<String> notifyResponse = appointmentService.appointmentPay(
                appointmentPayPojo.getOrganizationId(),
                appointmentPayPojo.getOrderId(),
                appointmentPayPojo.getOutOrderNumber(),
                appointmentPayPojo.getPayMode(),
                appointmentPayPojo.getAgtOrderNumber(),
                appointmentPayPojo.getPayAmount(),
                appointmentPayPojo.getPayTime(),
                appointmentPayPojo.getNotify(),
                appointmentPayPojo.getChannelOrderNumber(),
                appointmentPayPojo.getOutpatientType(),
                appointmentPayPojo.getEnterQueue()
        );

        logger.info("===== notifyResponse : {} ========",notifyResponse);
        if (notifyResponse.getCode() == Constant.errorTag) {
            entity.setCode(notifyResponse.getCode());
            entity.setMessage(notifyResponse.getMessage());
            return entity;
        }

        if (notifyResponse.getCode() != Constant.successTag) {

            entity.setMessage(notifyResponse.getMessage());

        }
        Map<String, String> repData = new HashMap<>();
        repData.put("registeredSerialNo", notifyResponse.getData());

        entity.setData(repData);


        return entity;

    }

    @ApiOperation(value = "挂号支付预结算/签到取号预结算",
            notes = "入参：hospitalCode：医院ID，医院系统身份标识 ; hisOrderNumber ：医院挂号流水号 ")
    @ResponseBody
    @RequestMapping(value = "/paymentBudget", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Object> paymentBudget(@RequestBody PaymentBudgetPojo paymentBudgetPojo) {
        //Map<String, Object> map = null;
        ResponseEntity<Object> entry = new ResponseEntity<>();

        BaseResponse<Map<String, Object>> response = new BaseResponse<>();

        try {

            response = TakenumberService.paymentBudget(paymentBudgetPojo);
            logger.info("====== paymentBudget response : {} ========",response);
        } catch (Exception e) {
            e.printStackTrace();
            entry.setCode(Constant.errorTag);
            entry.setMessage("处理失败");
        }
        if (response.getCode() == Constant.errorTag) {
            entry.setCode(response.getCode());
            entry.setMessage(response.getMessage());
            return entry;
        }
        if (response.getCode() != Constant.successTag) {

            entry.setMessage(response.getMessage());
            return entry;
        }
//		entry.setCode(ResponseStatus.SUCCESS_CODE);
//		entry.setMessage("处理成功");
        entry.setData(response.getData());

        return entry;
    }

//	@ApiOperation(value = "医生和科室查询", notes = "入参：hospitalCode：机构id ； query ：科室或者医生名称 ；outpatientType：门诊类型；")
//	@ResponseBody
//	@RequestMapping(value = "/queryDeptAndDoctor",method = RequestMethod.POST,produces = "application/json")
//	public ResponseEntity<List<DeptAndDoctorDomain>> queryDeptAndDoctor(@RequestBody QueryDeptAndDoctorPojo queryDeptAndDoctorPojo) {
//		
//		ResponseEntity<List<DeptAndDoctorDomain>> entry = new ResponseEntity();
//
//		List<DeptAndDoctorDomain> deptAndDoctorList = appointmentService.queryDeptAndDoctor(  
//			queryDeptAndDoctorPojo.getHospitalCode(),queryDeptAndDoctorPojo.getQuery(),	queryDeptAndDoctorPojo.getOutpatientType());
//		
//		entry.setData(deptAndDoctorList);
//
//		return entry;
//
//	}


    @ApiOperation(value = "4.1.13停诊通知  同步预约执行情况，把预约挂号的执行情况同步到预约系统",
            notes = "入参：startTime：开始时间 ; endTime ：结束时间 ")
    @RequestMapping(value = "/getCanceledWorks", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<List<CanceledWorks>> getCanceledWorks(@RequestBody GetCanceledWorksPojo getCanceledWorksPojo) {
        ResponseEntity<List<CanceledWorks>> entity = new ResponseEntity<>();
        List<CanceledWorks> canceledWorks = null;
        try {
            canceledWorksService.selectList(getCanceledWorksPojo.getBeginTime(),
                    getCanceledWorksPojo.getEndTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        entity.setData(canceledWorks);

        return entity;
    }


    @ApiOperation(value = "同步预约执行情况，把预约挂号的执行情况同步到预约系统",
            notes = "入参：hospitalCode：医院ID，医院系统身份标识 ; scheduleDate ：出诊日期; lastModifyTime:最后修改时间 ")
    @ResponseBody
    @RequestMapping(value = "/syncOrderState", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Object> syncOrderState(@RequestBody SyncOrderStatePoJo syncOrderStatePoJo) {
        ResponseEntity<Object> entry = new ResponseEntity<>();
        BaseResponse<List<SyncOrderState>> responseEntry = new BaseResponse<>();

        responseEntry = appointmentService.syncOrderState(syncOrderStatePoJo);

        if ("1".equals(responseEntry.getCode().toString())) {
            entry.setCode(ResponseStatus.SUCCESS_CODE);
        } else if ("0".equals(responseEntry.getCode().toString())) {
            entry.setCode(ResponseStatus.ERROR_CODE);
        }
        entry.setMessage(responseEntry.getMessage());
        entry.setData(responseEntry.getData());

        return entry;
    }

    @ApiOperation(value = "用户在医院退号退费后，需要his调用通知接口来推送app，做到退号通知",
            notes = "入参：hospitalCode：医院ID，医院系统身份标识 ; hisOrderNumber ：医院挂号流水号  ")
    @ResponseBody
    @RequestMapping(value = "/refundNotice", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Object> refundNotice(@RequestParam(value = "hospitalCode") String hospitalCode,
                                               @RequestParam(value = "hisOrderNumber") String hisOrderNumber) {

        Map<String, Object> map = null;
        ResponseEntity<Object> entry = new ResponseEntity<>();
        entry.setCode(ResponseStatus.SUCCESS_CODE);
        entry.setMessage("处理成功");

        try {
            map = appointmentService.refundNotice(hospitalCode, hisOrderNumber);
        } catch (Exception e) {
            e.printStackTrace();
            entry.setCode(ResponseStatus.ERROR_CODE);
            entry.setMessage("处理失败");
        }
        entry.setData(map);

        return entry;
    }

    /**
     * 预约挂号
     */
    @ApiOperation(value = "预约提交")
    @ResponseBody
    @RequestMapping(value = "/confirmAppointment", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<BookingRegisterDomain> confirmAppointment(@RequestBody BookingRegisterPojo bookingRegisterPojo) {
        logger.info("BookingRegisterPojo ----> {}",bookingRegisterPojo);
        ResponseEntity<BookingRegisterDomain> responseEntity = new ResponseEntity();
        try {
            BaseResponse<BookingRegisterDomain> baseResponse = appointmentService.saveYYGH(bookingRegisterPojo);
            if (baseResponse.getCode() == Constant.errorTag) {
                responseEntity.setCode(Constant.errorTag);
                responseEntity.setMessage(baseResponse.getMessage());
                return responseEntity;
            }
            responseEntity.setCode(Constant.successResponse);
            responseEntity.setMessage("请求成功");
            responseEntity.setData(baseResponse.getData());
        } catch (SQLException e) {
            responseEntity.setCode(Constant.errorTag);
            responseEntity.setMessage("数据库错误");
        } catch (NullPointerException e) {
            e.printStackTrace();
            responseEntity.setCode(Constant.errorTag);
            responseEntity.setMessage("参数错误");
        } catch (Exception e) {
            e.printStackTrace();
            responseEntity.setCode(Constant.errorTag);
            responseEntity.setMessage("请求失败");
        }

        return responseEntity;
    }

    @ApiOperation(value = "复诊配药支付通知")
    @ResponseBody
    @RequestMapping(value = "/returnVisitPaymentAndSettlement", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Map<String, Object>> returnVisitPaymentAndSettlement(@RequestBody ReturnVisitPaymentAndSettlementPojo returnVisit) {
        //Map<String, Object> map = null;
        ResponseEntity<Map<String, Object>> entry = new ResponseEntity<>();

        BaseResponse<String> response = new BaseResponse<>();

        try {

            response = appointmentService.returnVisitPaymentAndSettlement(returnVisit);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            entry.setCode(Constant.errorTag);
            entry.setMessage("处理失败");
        }
        logger.info("returnVisitPaymentAndSettlement response is {}",response);
        if (response.getCode() == Constant.errorTag) {
            entry.setCode(response.getCode());
            entry.setMessage(response.getMessage());
            return entry;
        }
        if (response.getCode() != Constant.successTag) {

            entry.setMessage(response.getMessage());
            return entry;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("registeredSerialNo", response.getData());
//			entry.setCode(ResponseStatus.SUCCESS_CODE);
//			entry.setMessage("处理成功");
        entry.setData(map);

        return entry;
    }

    /**
     * 获取停诊信息
     */
    @ApiOperation(value = "停诊信息获取")
    @ResponseBody
    @RequestMapping(value = "/getCanceledWorksDetail", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<CanceledWorksMainDomain> getCanceledWorks(@RequestBody CanceledWorksPojo canceledWorksPojo) {
        ResponseEntity<CanceledWorksMainDomain> entity = new ResponseEntity<>();
        CanceledWorksMainDomain canceledWorksMainDomain = new CanceledWorksMainDomain();
        BaseResponse<List<CanceledWorksDomain>> data = canceledWorksService.getCanceledWorksInfo(canceledWorksPojo);
        canceledWorksMainDomain.setOrderInformationList(data.getData());
        entity.setMessage(data.getMessage());
        entity.setCode(data.getCode());
        entity.setData(canceledWorksMainDomain);
        return entity;
    }

    /**
     * 医保签到
     *
     * @param appointmentSignPojo 签到参数
     * @return 医保周期号
     */
    @ApiOperation(value = "医保签到")
    @ResponseBody
    @RequestMapping(value = "/appointmentSign", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<String> signIn(@RequestBody AppointmentSignPojo appointmentSignPojo) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        String ybzqh = ybService.doQuerySFQD(appointmentSignPojo.getOrganizationId(), appointmentSignPojo.getManager());
        if (StringUtils.isNotBlank(ybzqh)) {
            responseEntity.setData(ybzqh);
        } else {
            responseEntity.setMessage(ResponseStatus.ERROR_MSG);
        }
        return responseEntity;
    }

    @ApiOperation(value = "医保签退")
    @ResponseBody
    @RequestMapping(value = "/appointmentSignOut", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<String> signOut(@RequestBody AppointmentSignPojo appointmentSignPojo){
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        boolean signOut = ybService.signOut(appointmentSignPojo.getOrganizationId(), appointmentSignPojo.getManager());
        if(signOut){
            responseEntity.setCode(ResponseStatus.SUCCESS_CODE);
            responseEntity.setData(String.valueOf(signOut));
            responseEntity.setMessage(ResponseStatus.SUCCESS_MSG);
        } else {
            responseEntity.setCode(ResponseStatus.ERROR_CODE);
            responseEntity.setMessage(ResponseStatus.ERROR_MSG);
        }
        return responseEntity;
    }
}
